package org.richin.io.image.util;

import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import javax.swing.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.Kernel;
import java.awt.image.ConvolveOp;

public class ImageUtil {

	public static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {

		if (quality < 0 || quality > 1) {
			throw new IllegalArgumentException("Quality has to be between 0 and 1");
		}

		ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
		Image i = ii.getImage();
		Image resizedImage = null;

		int iWidth = i.getWidth(null);
		int iHeight = i.getHeight(null);

		if (iWidth > iHeight) {
			resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);
		} else {
			resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);
		}

		// This code ensures that all the pixels in the image are loaded.
		Image temp = new ImageIcon(resizedImage).getImage();

		// Create the buffered image.
		BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB);

		// Copy image to buffered image.
		Graphics g = bufferedImage.createGraphics();

		// Clear background and paint the image.
		g.setColor(Color.white);
		g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
		g.drawImage(temp, 0, 0, null);
		g.dispose();

		// Soften.
		float softenFactor = 0.05f;
		float[] softenArray = { 0, softenFactor, 0, softenFactor, 1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0 };
		Kernel kernel = new Kernel(3, 3, softenArray);
		ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
		bufferedImage = cOp.filter(bufferedImage, null);

		// Write the jpeg to a file.
		FileOutputStream out = new FileOutputStream(resizedFile);

		// Encodes image as a JPEG data stream
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);

		param.setQuality(quality, true);

		encoder.setJPEGEncodeParam(param);
		encoder.encode(bufferedImage);
	}
	/**
	  * 生成以JPG编码的缩略图
	  * @param filename: 文件的全路径
	  * @param new_w: 新生成的图片的宽度，单位是像素
	  * @param new_h: 新生成的图片的高度，单位是像素
	  */
	 public void genPic(String filename, int new_w, int new_h) {
	  try {
	   // -----------------------开始生成缩略图-----------------

	   // 读入文件
	   java.io.File file = new java.io.File(filename);
	   // "c:/workspace/ec/1001.jpg" 经过下面一行代码之后变成 "c:/workspace/ec/"
	   String filePath = filename.substring(0,
	     filename.lastIndexOf("/") + 1);
	   // "c:/workspace/ec/1001.jpg" 经过下面一行代码之后变成 "1001"
	   String fileNameWithOutSubfix = filename.substring(filename
	     .lastIndexOf("/") + 1, filename.length() - 4);
	   // 新的缩略图保存地址
	   String newurl = filePath + "min_" + fileNameWithOutSubfix + ".jpg";
	   // 构造Image对象
	   Image imageSrc = javax.imageio.ImageIO.read(file);
	   float tagsize = 200;
	   // 得到源图宽，这里只为了校验文件是不是图片文件，如果不是，就直接异常了
	   int old_w = imageSrc.getWidth(null);
	   BufferedImage tag = new BufferedImage(new_w, new_h,
	     BufferedImage.TYPE_INT_RGB);
	   // 绘制缩小后的图
	   tag.getGraphics().drawImage(imageSrc, 0, 0, new_w, new_h, null);
	   // 输出到文件流
	   FileOutputStream newimage = new FileOutputStream(newurl);
	   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
	   // JPEG编码
	   encoder.encode(tag);
	   newimage.close();
	  } catch (IOException e) {
	   System.out.println("非图片文件：所传入的文件路径代表的文件不是图片文件，确定！！");
	   e.printStackTrace();
	  }
	 }

	 /**
	  * 校验一个文件是否是图片文件
	  * @param filename: 文件的全路径
	  * @return 如果是图片文件，则返回true，如果不是图片文件则返回false
	  */
	 public boolean isPic(String filename) {
	  try {
	   // 读入文件
	   java.io.File file = new java.io.File(filename);
	   Image imageSrc = javax.imageio.ImageIO.read(file);
	   // 得到源图宽
	   int old_w = imageSrc.getWidth(null);
	   return true;
	  } catch (IOException e) {
	   System.out.println("非图片文件：所传入的文件路径代表的文件不是图片文件，确定！！");
	   e.printStackTrace();
	   return false;
	  }
	 }


	// Example usage
	public static void main(String[] args) throws IOException {
		File originalImage = new File("D:/ssdf/ww.jpg");
		resize(originalImage, new File("D:/ssdf/untitled1.jpg"), 350, 0.7f);
		resize(originalImage, new File("D:/ssdf/untitled2.jpg"), 350, 1f);
	}
}